﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using TwitterTrendsSilverlightWebPart.Classes;

namespace TwitterTrendsSilverlightWebPart
{
    public partial class MainPage : UserControl
    {
        #region Internal and private members
        internal static readonly XNamespace ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
        internal static readonly XNamespace TWITTER_NAMESPACE = "http://api.twitter.com";
        private string hashTag = "SharePoint";
        private string numOfTweets = "15";
        #endregion

        #region Constructor
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        #endregion

        #region methods
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // checks if hashtag and number of tweets are passed from the object
            if ((App.Current as App).AppInitParams.ContainsKey("Hashtag"))
                hashTag = (App.Current as App).AppInitParams["Hashtag"];
            if ((App.Current as App).AppInitParams.ContainsKey("Tweets"))
                numOfTweets = (App.Current as App).AppInitParams["Tweets"];
            
            // loads the trends from Twitter API using WebClient
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
            wc.DownloadStringAsync(new Uri(string.Format("http://search.twitter.com/search.atom?q=%23{0}&rpp={1}&callback=?",hashTag,numOfTweets),UriKind.Absolute));
        }

        void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // parse the result as XDocument and then use linq to xml.
            XDocument result = XDocument.Parse(e.Result);
            var items = from x in result.Descendants(ATOM_NAMESPACE + "entry")
                        select new TweetItem
                        {
                            Author = (x.Element(ATOM_NAMESPACE + "author").FirstNode as XElement).Value,
                            AuthorURL = (x.Element(ATOM_NAMESPACE + "author").LastNode as XElement).Value,
                            Tweet = x.Element(ATOM_NAMESPACE + "title").Value,
                            ProfileImageUrl = x.Elements(ATOM_NAMESPACE + "link").Where(rel => (string)rel.Attribute("rel") == "image").Select(rel => (string)rel.Attribute("href")).First(),
                            Published = Convert.ToDateTime(x.Element(ATOM_NAMESPACE + "published").Value)
                        };

            // set the datacontext of the application to items
            this.DataContext = items.OrderBy(i => i.Published);
        }

        private void titleRect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // once the top blue bar is clicked - jump to the first item on the list.
            // TO-DO: Use animation!
            itemsListBox.ScrollIntoView(itemsListBox.Items[0]);
        }
        #endregion
    }
}
